package com.qf.controller;

import com.qf.util.RedisLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaojian
 */
@RestController
public class SeckillController {

    @Autowired
    private CuratorFramework cf;

    @Autowired
    private RedisLockUtil redisLockUtil;

    //模拟全局变量, 库存
    public static Map<String, Integer> stockCount = new HashMap<>();

    //模拟全局变量, 订单个数
    public static Map<String, Integer> orderCount = new HashMap<>();

    static {
        stockCount.put("牙刷", 100000);
        orderCount.put("牙刷", 0);
    }

    /**
     * 模拟秒杀下单方法
     * @param item
     * @return
     */
    @RequestMapping("/kill")
    public String kill(String item) throws Exception{

        //====================zookeeper加锁 begin=====================================
        //InterProcessMutex lock = new InterProcessMutex(cf, "/lock");

       // if (lock.acquire(1, TimeUnit.SECONDS)) {
            //====================zookeeper加锁 end=====================================

        //===================redis加锁  begin========================
        if (redisLockUtil.lock(item, String.valueOf(System.currentTimeMillis()), 1)) {
        //=====================redis加锁  end======================

            //获取库存, 扣减库存
            Integer stock = SeckillController.stockCount.get(item) - 1;
            stockCount.put(item, stock);

            //增加订单量
            Integer order = orderCount.get(item) + 1;
            orderCount.put(item, order);


            //====================zookeeper解锁 begin=====================================
            //lock.release();
            //====================zookeeper解锁 end=====================================

            //===============redis解锁  begin======================
            redisLockUtil.unlock(item);
            //==============redis解锁  end==========================
            return "下单成功: 库存剩余量:" + stock + "订单量:" + order;
        } else {
            return "下单失败!";
        }

    }
}
